//创建用户相关的笑场库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
//引入数据类型
import type { loginForm, responseData } from '@/api/user/type'
import type { UserState } from '../types/type'
//引入常量路由
import { constantRoute } from '@/router/router'
//创建小仓库
const useUserStore = defineStore('User', {
  //存储数据
  state: (): UserState => {
    return {
      idNumber: localStorage.getItem('token'), //用户唯一标识符
      menuRoutes: constantRoute, //生成菜单需要的数组路由
      userName: '', //用户名字
      avatar: '../../assets/images/avatar.jpg', //用户头像暂时无
    }
  },
  //异步
  actions: {
    //用户登录方法
    async userLogin(data: loginForm) {
      console.log(data)
      const result: responseData = await reqLogin(data)
      console.log(result)
      //要么成功1，失败0
      if (result.code == 1) {
        this.idNumber = result.data.id as string
        //本地存一下
        localStorage.setItem('token', result.data.id as string)
        return 'ok'
      } else {
        return Promise.reject(new Error(result.msg))
      }
    },
    //获取用户信息
    async userInfo() {
      //获取用户信息存储到仓库
      const result: responseData = await reqUserInfo(this.idNumber)
      localStorage.setItem('username', result.data.name as string) //小纯一下本地
      console.log(result.data.name)
      this.username = result.data.name
    },
    //退出登录
    async userLogout() {
      const result = await reqLogout()
      console.log(result.data)
      this.idNumber = ''
      this.username = ''
      localStorage.removeItem('token')
      localStorage.removeItem('username')
    },
  },
  getters: {},
})
//对外暴露获取笑场库
export default useUserStore
